﻿using System;
using System.Data;
using System.Configuration;
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MySql.Data.MySqlClient;
using LdExpress;
using System.IO;
using System.Globalization;

public partial class _Default : System.Web.UI.Page
{
    public string ContainerPage = "./PriceAreasNew.aspx";
    public string strCondition = "";
    public int NumOfItemsPerPage = 25;
    public string strPager = "";
    public string strError = "";
    public string strMess = "";
    public int nPermissions = 0;
    public int nPage = 1;
    public string strPageID = "page_number";
    string strExcluded = "";
    public string strPartQuery = "";
    public string strInforServiceAreas = "PRICE AREAS";
    public long lPolID = 0;
    public long lCarrID = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {

            if (Request.QueryString[strPageID] != null)
                nPage = int.Parse(Request.QueryString[strPageID]);
        }
        catch
        {
            nPage = 1;
        }
        if (nPage <= 0) nPage = 1;
        if (Session["logined_id"] != null)
        {
            if (Session["PriceAreasNew"] != "") nPermissions = int.Parse(Session["PriceAreasNew"].ToString());
            if (nPermissions <= 0) Response.Redirect("Login.aspx");
        }
        else
            Response.Redirect("Login.aspx");
        if (!Page.IsPostBack)
        {
            if (Session["PriceAreasCarr"] != null) lCarrID = int.Parse(Session["PriceAreasCarr"].ToString());
            if (Session["PriceAreasPol"] != null) lPolID = int.Parse(Session["PriceAreasPol"].ToString());
            lblerror.Text = "";
            if (nPermissions < 3)
                btnsave.Visible = false;
            //if (nPermissions < 9)
            //{
            //    ddCarr.Visible = true;
            //    ddPol.Visible = true;
            //    txtCarr.Visible = false;
            //    txtPol.Visible = false;
            //    btnSearh.Visible = false;
            //    loadDropDownCarr();
            //    loadDropDownPOL();
            //}
            //else
            //{
            //    ddCarr.Visible = false;
            //    ddPol.Visible = false;
            //    txtCarr.Visible = true;
            //    txtPol.Visible = true;
            //}
            if (Session["PriceAreasCarrName"] != null)
                txtCarr.Text = Session["PriceAreasCarrName"].ToString();
            if (Session["PriceAreasPolName"] != null)
                txtPol.Text = Session["PriceAreasPolName"].ToString();
            if (Session["PriceAreasServiceCode"] != null)
                txtServiceArea.Text = Session["PriceAreasServiceCode"].ToString();
            if (Request.QueryString["action"] == "delete" && nPermissions >= 9)
            {
                PriceAreasNew obj = new PriceAreasNew();
                obj.ID = long.Parse(Request.QueryString["ID"]);
                obj.Delete(GV.cn, GV.trans);
                UserObjectsLog.SaveObjectActionLog(long.Parse(Session["logined_id"].ToString()), "PriceAreas", "Delete", GV.cn, GV.trans);
                Response.Redirect("PriceAreasNew.aspx" + ((Request.QueryString["page_number"] != null && Request.QueryString["page_number"].ToString() != "") ? "?page_number=" + Request.QueryString["page_number"].ToString() : ""));
            }
            if (Request.QueryString["action"] == "public")
            {
                PriceAreasNew obj = new PriceAreasNew();
                obj.ID = long.Parse(Request.QueryString["ID"].ToString());
                obj.Load(GV.cn, GV.trans);
                string tempDt = "";
                string tempRate = "";
                if (obj.DC20.Length > 10)
                {
                    tempDt = obj.DC20.Split('_')[1].ToString();
                    tempDt = tempDt.Substring(tempDt.Length - 10).Trim();
                    tempRate = obj.DC20.Split('_')[0].ToString();
                    GoodPricesNotice.PublicGoodPriceNoticeFromAreasNew(obj, tempDt, tempRate, "20'DC");
                }
                if (obj.DC40.Length > 10)
                {
                    tempDt = obj.DC40.Split('_')[1].ToString();
                    tempDt = tempDt.Substring(tempDt.Length - 10).Trim();
                    tempRate = obj.DC40.Split('_')[0].ToString();
                    GoodPricesNotice.PublicGoodPriceNoticeFromAreasNew(obj, tempDt, tempRate, "40'DC");
                }
                if (obj.HC40.Length > 10)
                {
                    tempDt = obj.HC40.Split('_')[1].ToString();
                    tempDt = tempDt.Substring(tempDt.Length - 10).Trim();
                    tempRate = obj.HC40.Split('_')[0].ToString();
                    GoodPricesNotice.PublicGoodPriceNoticeFromAreasNew(obj, tempDt, tempRate, "40'HC");
                }
                if (obj.RF20.Length > 10)
                {
                    tempDt = obj.RF20.Split('_')[1].ToString();
                    tempDt = tempDt.Substring(tempDt.Length - 10).Trim();
                    tempRate = obj.RF20.Split('_')[0].ToString();
                    GoodPricesNotice.PublicGoodPriceNoticeFromAreasNew(obj, tempDt, tempRate, "20'RF");
                }
                if (obj.RF40.Length > 10)
                {
                    tempDt = obj.RF40.Split('_')[1].ToString();
                    tempDt = tempDt.Substring(tempDt.Length - 10).Trim();
                    tempRate = obj.RF40.Split('_')[0].ToString();
                    GoodPricesNotice.PublicGoodPriceNoticeFromAreasNew(obj, tempDt, tempRate, "40'RF");
                }
                Response.Redirect("PriceAreasNew.aspx" + ((Request.QueryString["page_number"] != null && Request.QueryString["page_number"].ToString() != "") ? "?page_number=" + Request.QueryString["page_number"].ToString() : ""));
            }
            LoadBuildList();
        }
    }
    private void LoadBuildList()
    {
        #region Build List
        int nNumOfPages = 0;

        DataTable dtList;
        BuildList(NumOfItemsPerPage, nPage, out nNumOfPages, out dtList, GV.cn, GV.trans);
        if (nPage > nNumOfPages) nPage = 1;

        rptData.DataSource = dtList;
        rptData.DataBind();
        #endregion
        #region Build Pager
        CommonFunctions.BuildPager(Request, nNumOfPages, nPage, strPageID, ContainerPage, out strPager);
        #endregion
    }
    private void BuildList(int NumOfItemsPerPage, int PageNo, out int nNumOfPages, out DataTable dtList, MySqlConnection cn, MySqlTransaction trans)
    {
        DataSet ds = null;
        dtList = new DataTable();
        dtList.Columns.Add("ID");
        dtList.Columns.Add("Index");
        dtList.Columns.Add("DC20");
        dtList.Columns.Add("DC40");
        dtList.Columns.Add("HC40");
        dtList.Columns.Add("Validity");
        dtList.Columns.Add("ValidityEx");
        dtList.Columns.Add("RF20");
        dtList.Columns.Add("RF40");
        dtList.Columns.Add("Note");
        dtList.Columns.Add("NoteEx");
        dtList.Columns.Add("LastUpdate");
        dtList.Columns.Add("SerAreaID");
        dtList.Columns.Add("SerAreaName");
        dtList.Columns.Add("PolID");
        dtList.Columns.Add("PolName");
        dtList.Columns.Add("PodIncluded");
        dtList.Columns.Add("CarrID");
        dtList.Columns.Add("Carr");
        dtList.Columns.Add("Action");
        nNumOfPages = 0;

        //string strOrderBy = "CarrName,LastUpdate Desc";
        bool bDisplay = false;
        if (Session["PriceAreasCarr"] != null && int.Parse(Session["PriceAreasCarr"].ToString()) > 0)
        {
            strCondition += " AND CarrID=" + Session["PriceAreasCarr"].ToString() + " AND PolID=" + Session["PriceAreasPol"].ToString();
            bDisplay = true;
        }
        if (Session["PriceAreasPol"] != null && int.Parse(Session["PriceAreasPol"].ToString()) > 0)
        {
            strCondition += " AND PolID=" + Session["PriceAreasPol"].ToString();
            bDisplay = true;
        }
        if (Session["PriceAreasServiceCode"] != null && Session["PriceAreasServiceCode"].ToString().Length > 0)
        {
            strCondition += " AND SerAreas.Code like '%" + Session["PriceAreasServiceCode"].ToString() + "%'";
        }

        if (!bDisplay)
            strCondition = " AND 1=0";
        PriceAreasNew.GetList(strCondition, " ID ASC", NumOfItemsPerPage, PageNo, out nNumOfPages, out ds, GV.cn, GV.trans);

        string strAllQueryString = "";
        foreach (string strKey in Request.QueryString.AllKeys)
        {
            if (strKey != null)
            {
                if ((strKey.ToLower() != "action") && (strKey.ToLower() != "id"))
                    strAllQueryString = strAllQueryString + "&" + strKey + "=" + Request.QueryString[strKey].ToString();
            }
        }

        if (strAllQueryString.Length >= 1)
            strAllQueryString = strAllQueryString.Substring(1);
        if (ds != null && ds.Tables[0].Rows.Count > 0)
        {
            GetInforServiceAreas();
            int count = 0;
            if (Request.QueryString["page_number"] != null && Request.QueryString["page_number"].ToString() != "")
            {
                int pagenumber = 1;
                try
                {
                    pagenumber = int.Parse(Request.QueryString["page_number"]);
                    count = NumOfItemsPerPage * (pagenumber - 1);
                }
                catch { count = 0; }
            }
            DataSet objds = null;

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                objds = new DataSet();

                count++;
                string strID = dr["ID"].ToString();
                string strIndex = count.ToString();
                string strDC20 = dr["DC20"].ToString();
                string strDC40 = dr["DC40"].ToString();
                string strHC40 = dr["HC40"].ToString();
                string strValidity = dr["Validity"].ToString();
                string strValidityEx = dr["ValidityEx"].ToString();
                string strRF20 = dr["RF20"].ToString();
                string strRF40 = dr["RF40"].ToString();
                string strNote = dr["Note"].ToString();
                string strNoteEx = dr["NoteEx"].ToString();
                string strPolID = dr["PolID"].ToString();
                string strPolName = dr["PolName"].ToString();
                string strCarrID = dr["CarrID"].ToString();
                string strCarrName = dr["CarrName"].ToString();
                string strSeviceAreaID = dr["ServiceAreaID"].ToString();
                string strSeviceAreasName = dr["ServiceAreaNameSource"].ToString();
                string strSeviceAreasCode = dr["ServiceAreaCodeSource"].ToString();
                string strPodIncluded = dr["PodIncluded"].ToString();
                string strLastUpdate = "";
                if (dr["LastUpdate"].ToString() != "")
                {
                    DateTime dt = DateTime.Parse(dr["LastUpdate"].ToString());
                    if (dt > DateTime.MinValue)
                        strLastUpdate = dt.ToString("ddMMyyyy");
                }
                string strAction = "<div class=\"changed\">";
                string strTemp = "";
                //if (nPermissions >= 3)
                //{
                //    //get public
                //    if (dr["LastUpdate"].ToString().Length > 0)
                //    {
                //        DateTime dtLst = DateTime.Parse(dr["LastUpdate"].ToString());
                //        if (dtLst.AddDays(7) >= DateTime.Now)
                //        {
                //            strAction += "<a href=\"javascript:doPublic('" + System.Web.HttpUtility.HtmlEncode(dr["ID"].ToString()) + "','" + System.Web.HttpUtility.HtmlEncode(strTemp) + "')\">Public</a>";
                //        }
                //    }
                //}
                if (nPermissions > 7)
                {
                    strAction += " <a href=\"PriceAreasNew.aspx?action=delete&ID=" + dr["ID"].ToString() + "\"> Delete </a>";
                }
                strAction += "</div>";
                string[] strValues = new string[] { strID, strIndex
                    , strDC20, strDC40, strHC40,strValidity,strValidityEx, strRF20, strRF40,strNote,strNoteEx
                    , strLastUpdate,strSeviceAreaID,strSeviceAreasCode, strPolID,strPolName,strPodIncluded,strCarrID,strCarrName, strAction };
                dtList.Rows.Add(strValues);
            }
        }
        if (nPermissions > 3)
            if (Session["PriceAreasCarr"] != null && int.Parse(Session["PriceAreasCarr"].ToString()) > 0 &&
                Session["PriceAreasPol"] != null && int.Parse(Session["PriceAreasPol"].ToString()) > 0)
                dtList.Rows.Add(new string[] { "-1", "<a href=\"#\" onclick=\"NewLine();\" class=\"newrow\">+</a>", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" });
        //dtList.Rows.Add(new string[] { "-1", "<input type=\"button\" name=\"add\" value=\"Add\" class=\"tr_clone_add\">", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" });
    }
    public string GetCellTitle(object inputstring)
    {
        string title = "";
        if (inputstring != null && !string.IsNullOrEmpty(inputstring.ToString()))
        {
            string[] arrUpdate = inputstring.ToString().Split('_');
            if (arrUpdate.Length > 1)
                title = arrUpdate[1];
        }
        return title;
    }
    public string GetCellClass(object inputstring)
    {
        string className = "";
        if (inputstring != null && !string.IsNullOrEmpty(inputstring.ToString()))
        {
            string[] arrUpdate = inputstring.ToString().Split('_');
            if (arrUpdate.Length > 1 && arrUpdate[0].Length > 0)
            {
                try
                {
                    string tempDt = arrUpdate[1].Substring(arrUpdate[1].Length - 10).Trim();
                    DateTime dt = DateTime.ParseExact(tempDt, "dd-MM-yyyy", CultureInfo.InvariantCulture);
                    if (dt.AddDays(7) >= DateTime.Now)
                        className = "has-value-lastweek";
                    else if (dt.AddDays(14) >= DateTime.Now && dt.AddDays(7) < DateTime.Now)
                        className = "has-value-last2week";
                    else
                        className = "has-value";
                }
                catch
                {
                    className = "";
                }
            }
        }
        return className;
    }
    public string GetCellValue(object inputstring, bool emptyIfNull = false)
    {
        string cellvalue = !emptyIfNull ? "No check" : "";
        if (inputstring != null && inputstring.ToString().Trim().Length > 0)
        {
            string[] arrUpdate = inputstring.ToString().Split('_');
            if (arrUpdate[0].Length > 0)
                cellvalue = arrUpdate[0];
        }
        return cellvalue;
    }
    private void GetInforServiceAreas()
    {
        strInforServiceAreas = "PRICE AREAS";
        if (Session["PriceAreasCarrName"] != null && Session["PriceAreasCarrName"].ToString().ToLower() != "carriers")
        {
            if (Session["PriceAreasPol"] != null && Session["PriceAreasPol"].ToString() != "")
                strInforServiceAreas = "EXPORT: " + Session["PriceAreasCarrName"].ToString() + " - " + Session["PriceAreasPolName"].ToString();
            if (Session["PriceAreasPod"] != null && Session["PriceAreasPod"].ToString() != "")
                strInforServiceAreas = "IMPORT: " + Session["PriceAreasCarrName"].ToString() + " - " + Session["PriceAreasPodName"].ToString();
        }
        strInforServiceAreas = strInforServiceAreas.ToUpper();
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        lblerror.Text = "";

        if (txtCarr.Text.Trim().Length > 0)
        {
            Carrs objCarr = new Carrs();
            objCarr.Load(txtCarr.Text.Trim(), GV.cn, GV.trans);
            if (objCarr.ID <= 0)
            {
                lblerror.Text = "CARR không đúng.";
            }
            Session["PriceAreasCarr"] = objCarr.ID;
            Session["PriceAreasCarrName"] = objCarr.Name;
            lCarrID = int.Parse(Session["PriceAreasCarr"].ToString());
        }
        else
        {
            Session["PriceAreasCarr"] = 0;
            Session["PriceAreasCarrName"] = null;
            lCarrID = 0;
        }
        if (txtPol.Text.Trim().Length > 0)
        {
            Ports objPort = new Ports();
            objPort.Load(txtPol.Text.Trim(), GV.cn, GV.trans);
            if (objPort.ID <= 0)
            {
                lblerror.Text = "POL không đúng.";
            }
            Session["PriceAreasPol"] = objPort.ID;
            Session["PriceAreasPolName"] = objPort.Name;
            lPolID = int.Parse(Session["PriceAreasPol"].ToString());

        }
        else
        {
            Session["PriceAreasPol"] = 0;
            Session["PriceAreasPolName"] = null;
            lPolID = 0;
        }
        //Servic Area

        if (txtServiceArea.Text.Length > 0)
        {
            //ServiceAreas objSer = new ServiceAreas();
            //objSer.Load(txtServiceArea.Text, GV.cn, GV.trans);
            //if (objSer.ID > 0)
            //{
            //    Session["PriceAreasService"] = objSer.ID;
            //    Session["PriceAreasServiceCode"] = objSer.Name;
            //}
            Session["PriceAreasServiceCode"] = txtServiceArea.Text;
        }
        else
        {
            Session["PriceAreasService"] = 0;
            Session["PriceAreasServiceCode"] = null;
        }
        LoadBuildList();
    }
    //protected void loadDropDownCarr()
    //{
    //    string sqlCommand = "SELECT DISTINCT Carr.ID,Carr.Name FROM `tbl_priceareasnew` LEFT JOIN tbl_carrs Carr ON tbl_priceareasnew.CarrID = Carr.ID;";
    //    DataSet ds = DBModule.ExecuteQuery(sqlCommand, GV.cn, GV.trans);
    //    ddCarr.DataSource = ds.Tables[0];
    //    ddCarr.DataValueField = ds.Tables[0].Columns[0].ToString();
    //    ddCarr.DataTextField = ds.Tables[0].Columns[1].ToString();
    //    ddCarr.DataBind();
    //    ddCarr.Items.Insert(0, new ListItem("Select Carr", "0"));
    //    if (Session["PriceAreasCarr"] != null)
    //    {
    //        if (ddCarr.Items.FindByValue(Session["PriceAreasCarr"].ToString()) != null)
    //            ddCarr.SelectedValue = Session["PriceAreasCarr"].ToString();
    //    }
    //}
    //protected void loadDropDownPOL()
    //{
    //    string sqlCommand = "SELECT DISTINCT POL.ID,POL.Name FROM `tbl_priceareasnew` LEFT JOIN  tbl_Ports POL ON tbl_priceareasnew.PolID = POL.ID WHERE 1=1";
    //    if (Session["PriceAreasCarr"] != null && int.Parse(Session["PriceAreasCarr"].ToString()) > 0)
    //        sqlCommand += " AND tbl_priceareasnew.CarrID=" + Session["PriceAreasCarr"].ToString();
    //    DataSet ds = DBModule.ExecuteQuery(sqlCommand, GV.cn, GV.trans);
    //    ddPol.DataSource = ds.Tables[0];
    //    ddPol.DataValueField = ds.Tables[0].Columns[0].ToString();
    //    ddPol.DataTextField = ds.Tables[0].Columns[1].ToString();
    //    ddPol.DataBind();
    //    ddPol.Items.Insert(0, new ListItem("Select Pol", "0"));
    //    if (Session["PriceAreasPol"] != null)
    //    {
    //        if (ddPol.Items.FindByValue(Session["PriceAreasPol"].ToString()) != null)
    //            ddPol.SelectedValue = Session["PriceAreasPol"].ToString();
    //    }
    //}
    //protected void ddCarr_SelectedIndexChanged(object sender, EventArgs e)
    //{
    //    Session["PriceAreasCarr"] = ddCarr.SelectedValue;
    //    Session["PriceAreasCarrName"] = ddCarr.Text;
    //    //Clear POL
    //    Session["PriceAreasPol"] = 0;
    //    Session["PriceAreasPolName"] = "";
    //    Response.Redirect("PriceAreasNew.aspx");
    //}
    //protected void ddPol_SelectedIndexChanged(object sender, EventArgs e)
    //{
    //    Session["PriceAreasPol"] = ddPol.SelectedValue;
    //    Session["PriceAreasPolName"] = ddPol.Text;
    //    Response.Redirect("PriceAreasNew.aspx");
    //}
}
